<template>
  <view>
    <!-- 顶部tab栏 -->
    <view class="tabnav">
      <view
        :class="['nav_item', index === count ? 'active' : '']"
        v-for="(item, index) in menu"
        :key="index"
        @click="hendelNav(index)"
      >
        {{ item }}
      </view>
    </view>
    <view class="content_list">
      <view class="list" v-if="count === 0">
        <goodsitem
          v-for="(item, index) in goodsList"
          :key="index"
          :item="item"
        ></goodsitem>
      </view>
      <view class="list" v-if="count === 1">
        <goodsitem
          v-for="(item, index) in goodsList"
          :key="index"
          :item="item"
        ></goodsitem>
      </view>
      <view class="list" v-if="count === 2"> 33</view>
    </view>
  </view>
</template>

<script>
import goodsitem from "../../components/goods_item";
export default {
  components: {
    goodsitem,
  },
  data() {
    return {
      menu: ["综合", "销量", "价格"],
      count: 0,
      goodsList: [], // 商品数据
      params: {
        query: "", //	关键字
        cid: "", //	分类id
        pagenum: 1, //	页码
        pagesize: 10, //	页容量
      },
      totalPages: 0, // 总页数
    };
  },
  onLoad(options) {
    console.log(options);
    const id = options.id || 10;
    this.params.cid = id;
    this.getList();
  },
  methods: {
    hendelNav(index) {
      this.count = index;
    },
    async onPullDownRefresh() {
      console.log("下拉");
      uni.showToast({
        title: "刷新成功",
        icon: "none",
      });
      this.params.pagenum = 1;
      this.goodsList = [];
      await this.getList();
      // 停止下拉刷新
      uni.stopPullDownRefresh();
    },
    // 滚动条触底事件
    async onReachBottom() {
      console.log("滚动条触底事件");
      wx.showLoading({
        title: "加载下一页",
      });
      // 如果当总页数大于当前页数说明还有数据继续加载一页
      if (this.totalPages > this.params.pagenum) {
        this.params.pagenum++;
        await this.getList();
        uni.hideLoading();
      } else {
        uni.showToast({
          title: "没有下一页了",
          icon: "none",
        });
      }
    },
    // 商品列表数据请求
    async getList() {
      const res = await uni.request({
        url: "https://api-hmugo-web.itheima.net/api/public/v1/goods/search",
        data: this.params,
        method: "GET",
      });
      this.goodsList = [...res[1].data.message.goods, ...this.goodsList];
      // 计算总页数
      this.totalPages = Math.ceil(
        res[1].data.message.total / this.params.pagesize
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.tabnav {
  height: 42rpx;
  font-size: 30rpx;
  padding: 30rpx 50rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .nav_item {
    padding: 20rpx 50rpx;
  }
}
.active {
  border-bottom: 2px solid #eb4450;
}
.content_list {
  padding: 20rpx 40rpx;
}
</style>
